package com.asset.admin.filter;

import com.alibaba.druid.util.StringUtils;
import com.asset.common.config.Conts;
import com.asset.common.utils.CookieUtil;
import com.asset.common.utils.DomainUtil;
import com.asset.common.utils.ThreadLocalUtil;
import com.asset.common.utils.encrypt.EncryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;


@Service
@Slf4j
public class AssetFilter implements Filter {

    private static final Set<String> ALLOW_ORIGINS = new HashSet<>();

    //排除的url
    private static final Set<String> EXCLUDE_URLS = new HashSet<>();

    private static final String LOGIN_URI = "http://localhost:8080/";

    static {
        EXCLUDE_URLS.add("/login/login");
        EXCLUDE_URLS.add("/common/tradingdirectiontypes.json");
        EXCLUDE_URLS.add("/common/transactiontypes.json");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //走登陆是要种cookie
        //其他的url是要检查cookie
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String originHeader = request.getHeader("Origin");

        response.setHeader("Access-Control-Allow-Origin", originHeader); // 当前请求的来源
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH"); // 允许的 HTTP 方法
        response.setHeader("Access-Control-Allow-Credentials", "true"); // 允许携带凭证

        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept"); // 合并请求头设置
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK); // 返回 200 OK
            response.setHeader("Access-Control-Allow-Origin", originHeader);
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            return; // 结束处理
        }
        //设置domain
        String domain = DomainUtil.getDomain(request);
        ThreadLocalUtil.getInstance().set(Conts.ROOT_DOMAIN,domain);
        //获取url
        String servletPath = request.getServletPath();
        if(!needFilter(servletPath)){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        Cookie cookie = CookieUtil.getCookie(request, Conts.CURRENT_USER_ID);
        if(cookie == null){
            response.sendError(SC_UNAUTHORIZED);
            return;
        }
        if(Conts.CURRENT_USER_ID.equals(cookie.getName())){

            ThreadLocalUtil.getInstance().set(Conts.CURRENT_USER_ID, EncryptUtil.decrypt(cookie.getValue(),"resultUserEntity"));
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

    private void allowCORS(HttpServletRequest request, HttpServletResponse response) {
        String originHeader = request.getHeader("Origin");

        response.setHeader("Access-Control-Allow-Origin", originHeader); // 当前请求的来源
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH"); // 允许的 HTTP 方法
        response.setHeader("Access-Control-Allow-Credentials", "true"); // 允许携带凭证

        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept"); // 合并请求头设置
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK); // 返回 200 OK
            response.setHeader("Access-Control-Allow-Origin", originHeader);
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            return; // 结束处理
        }
    }


    private boolean needFilter(String requestUri) {
        if (StringUtils.isEmpty(requestUri)) {
            return true;
        }
        AntPathMatcher matcher = new AntPathMatcher();
        for (String pattern : EXCLUDE_URLS) {
            if (matcher.match(pattern, requestUri)) {
                return false;
            }
        }
        return true;
    }
}
